/*
 * 用户注册界面
 */
package com.cqtczh.qhd.driver.acticity.user;

import httptools.HttpJsonTool;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import tools.InvitationCode;
import tools.L;

import javabeen.RegisterBeen;
import javabeen.UserInfoBeen;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.http.RequestParams;
import com.cqtczh.qhd.driver.AppContent;
import com.cqtczh.qhd.driver.R;
import com.cqtczh.qhd.driver.acticity.AboutUsActivity;
import com.cqtczh.qhd.driver.acticity.base.BaseActivity;
import com.cqtczh.qhd.driver.api.GagApi;
import com.cqtczh.qhd.driver.model.LoginUserInfo;
import com.cqtczh.qhd.driver.utils.Base64Util;
import com.cqtczh.qhd.driver.utils.SMSBroadcastReceiver;
import com.cqtczh.qhd.driver.utils.SPUtils;
import com.cqtczh.qhd.driver.utils.StringUtils;

public class UserRegisterActivity extends BaseActivity implements
		OnClickListener {

	// 新服务器需要的
	private HttpJsonTool httpJsonToolGetcode;
	private TextView title;
	private Button user_reg, register_sms_ma;
	// 新服务器需要的
	private AppContent app;
	private TabHost mTabHost;
	private RadioGroup mRadioGroup;
	private TextView head_right;
	private ImageView head_left;

	private String mobile, password, idCard, realName;
	private EditText register_id, register_psw, register_sms, register_name,
			register_card, register_team, register_repsw;
	private Gson gson = new Gson();
	private HttpUtils http = new HttpUtils();
	private RequestParams params;
	private int mReSendTime = 60;
	// 标记是否被标记
	private boolean flag = false;
	/**
	 * 短信拦截
	 */
	private SMSBroadcastReceiver mSMSBroadcastReceiver;

	private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";

	@SuppressLint("NewApi")
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ly_register);
		System.out.println("regsiter");
		app = (AppContent) getApplication();
		title = (TextView) findViewById(R.id.head_title);
		head_left = (ImageView) findViewById(R.id.head_left);
		head_right = (TextView) findViewById(R.id.head_right);
		register_psw = (EditText) findViewById(R.id.register_psw);
		register_id = (EditText) findViewById(R.id.register_id);
		register_sms = (EditText) findViewById(R.id.register_sms);
		register_name = (EditText) findViewById(R.id.register_name);
		register_card = (EditText) findViewById(R.id.register_card);
		register_team = (EditText) findViewById(R.id.register_team);
		register_sms_ma = (Button) findViewById(R.id.register_sms_ma);
		user_reg = (Button) findViewById(R.id.register_zhuce);
		register_repsw = (EditText) findViewById(R.id.register_repsw);
		head_left.setVisibility(0);
		title.setText("司机注册");
		head_right.setOnClickListener(this);
		head_left.setOnClickListener(this);
		user_reg.setOnClickListener(this);
		register_sms_ma.setOnClickListener(this);
		Ini();
		startMSMReceiver();
	}

	private void Ini() {
		TextView register_deal_TextView = (TextView) findViewById(R.id.register_deal_TextView);
		// 跳转到用户协议界面
		register_deal_TextView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent dealIntent = new Intent();
				dealIntent.setClass(UserRegisterActivity.this,
						AboutUsActivity.class);
				dealIntent.putExtra("mark", "用户协议");
				startActivity(dealIntent);
			}
		});
		final ImageButton register_deal = (ImageButton) findViewById(R.id.imagebutton_register_deal);
		register_deal.setImageResource(R.drawable.unchecked);
		register_deal.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub

				if (flag) {
					register_deal.setImageResource(R.drawable.unchecked);
					flag = false;
				} else {
					register_deal.setImageResource(R.drawable.check);
					flag = true;
				}
			}
		});
		httpJsonToolGetcode = new HttpJsonTool(this, true);
		httpJsonToolGetcode.SetOnLister(new Handler() {
			// if()
			// goNext();
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				if (msg.what == 1) {
					showLongToast("成功获得验证码，请等待验证短信");
				} else {
					Toast.makeText(UserRegisterActivity.this, "请检查您的手机号码输入是否有误或者是否重复注册",
							Toast.LENGTH_SHORT).show();
				}
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.head_left:
			finish();
			break;
		case R.id.head_right:
		case R.id.register_zhuce:
			if (flag) {
				reg();
			} else {
				Toast.makeText(this, "请仔细阅读用户协议，后点同意！！！", Toast.LENGTH_LONG)
						.show();
			}

			break;
		case R.id.register_sms_ma:
			mobile = register_id.getText().toString().trim();
			if (StringUtils.isEmpty(mobile)) {
				showLongToast("请填写手机号码");
				return;
			} else
				getCode();
			break;
		default:
			break;
		}
	}

	private void reg() {
		// openActivity(MessageActivity.class);
		//List<UserID> userIDs = new ArrayList<UserID>();
		final RegisterBeen registerBeen = check();
		if (registerBeen != null) {
			showLoadingDialog("注册中...");
			HttpJsonTool tool = new HttpJsonTool(this);
			tool.SetOnLister(new Handler() {
				@Override
				// 返还数据，没有数据可以不用
				public void handleMessage(Message msg) {
					// TODO Auto-generated method stub
					super.handleMessage(msg);
					if (msg.what == 1) {
						Toast.makeText(UserRegisterActivity.this,
								"注册成功,请输入您的个人信息以供验证", Toast.LENGTH_LONG).show();
						// userIDs=msg.obj
						dismissLoadingDialog();
						HashMap<String, Object> data = new HashMap<String, Object>();
						data.put("password", registerBeen.getPassword());
						data.put("phone", InvitationCode.deCode(registerBeen.getPhone())+"");
						SeaveUserInfo(data);
					} else {
						Toast.makeText(UserRegisterActivity.this, (String)msg.obj, Toast.LENGTH_LONG).show();
						dismissLoadingDialog();
					}
				}
			});

			tool.StartWork(registerBeen,// 192.168.1.122"http://192.168.1.121:8080/cqtczh/fleets/register.do"
					GagApi.REGISTER, null, null);
		}
	}

//	/**
//	 * 
//	 * @Title: getCode
//	 * @Description: TODO(注册完成后登录)
//	 * @param 参数说明
//	 * @return void 返回类型
//	 * @throws
//	 */
//	private void Login(final Map<String, Object> dataMap) {
//		new ArrayList<LoginUserInfo>();
//		Type type = new TypeToken<List<UserInfoBeen>>() {
//		}.getType();
//		// SeaveUserInfo(dataMap);
//		HttpJsonTool httpJsonToos = new HttpJsonTool(this);
//		httpJsonToos.SetOnLister(new Handler() {
//			@Override
//			public void handleMessage(Message msg) {
//				// TODO Auto-generated method stub
//				super.handleMessage(msg);
//				if (msg.what == 1) {
//					// app.userInfoBeen
//					List<UserInfoBeen> d = (List<UserInfoBeen>) msg.obj;
//					app.userInfoBeen = d.get(0);
//					app.userId = d.get(0).getCarownerid() + "";
//					SeaveUserInfo(dataMap);
//				} else {
//					Toast.makeText(UserRegisterActivity.this, (String) msg.obj,
//							Toast.LENGTH_LONG).show();
//				}
//			}
//		});
//		httpJsonToos.StartWork(dataMap, GagApi.LOGIN, type, null);
//	}

	// 保存用户密码和id
	private void SeaveUserInfo(Map<String, Object> dataMap) {
		SPUtils.put(UserRegisterActivity.this, "phone", dataMap.get("phone"));
		SPUtils.put(UserRegisterActivity.this, "password",
				Base64Util.toHex((String) dataMap.get("password")));
		Intent intent = new Intent(UserRegisterActivity.this,
				MessageActivity.class);
		intent.putExtra("user_reg", "注册");
		startActivity(intent);
		// openActivity(MessageActivity.class);
		UserRegisterActivity.this.finish();
		// AppContent.setPhoneNO((String) dataMap.get("driverMobile"));
		// L.v("driverPassword", (String) dataMap.get("driverMobile"));
		// openActivity(ProjectHomeActivity.class);
		// openActivity(MessageActivity.class);
		// this.finish();
	}

	private void getCode() {

		// Map<String, Object> map=new HashMap<String, Object>();
		// map.put("", "");\

		goNext();
		RegisterBeen registerBeen = new RegisterBeen();
		registerBeen.setPhone(InvitationCode.enCode(register_id.getText().toString()));
		registerBeen.setType("1");
//		HashMap< String, Object> data=new HashMap<String, Object>();
//		data.put(key, value);
//		data.put(key, value);
		httpJsonToolGetcode.StartWork(registerBeen, GagApi.GETCODE, null, null);
	}

	protected void goNext() {
		new CountDownTimer(60 * 1000, 1000) {
			@Override
			public void onFinish() {
				// done
				mReSendTime = 60;
				register_sms_ma.setEnabled(true);
				register_sms_ma.setText("发送验证码");
			}

			@Override
			public void onTick(long arg0) {
				// 每1000毫秒回调的方法
				register_sms_ma.setEnabled(false);
				register_sms_ma.setText("" + mReSendTime--);
			}

		}.start();
	}

	// 检测数据是否为空
	private RegisterBeen check() {

		RegisterBeen registerBeen = new RegisterBeen();
		registerBeen.setType("1");
		if (StringUtils.isEmpty(register_id.getText().toString())||(register_id.getText().length()!=11)) {
			showLongToast("请填写正确的手机号码");
			return null;
		} else {
			registerBeen.setPhone(InvitationCode.enCode(register_id.getText().toString()));
		}
		if (StringUtils.isEmpty(register_sms.getText().toString())) {
			showLongToast("请填写验证码");
			return null;
		} else {
			registerBeen.setValidateCode(register_sms.getText().toString());
		}
		if (StringUtils.isEmpty(register_psw.getText().toString())||(register_psw.getText().length()<3)) {
			showLongToast("请填写密码，密码至少3位");
			return null;
		} else {
			String one_ps = register_psw.getText().toString();
			String two_ps = register_repsw.getText().toString();
			if ((two_ps.equals(one_ps)) && (one_ps.length() > 0)
					&& (two_ps.length() > 0)) {

				registerBeen.setPassword(register_psw.getText().toString());
			} else {
				Toast.makeText(this, "2次输入的密码不一致请检查！", Toast.LENGTH_LONG)
						.show();
				return null;
			}

		}
		if (!StringUtils.isEmpty(register_team.getText().toString())) {
			registerBeen.setInvitationCode(register_team.getText().toString());
		}
		return registerBeen;
	}
	
	
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}

	private void startMSMReceiver() {
//		Intent intent = new Intent();  
//        intent.setAction("android.intent.action.CALL");  
//        this.sendBroadcast(intent);  
		mSMSBroadcastReceiver=new SMSBroadcastReceiver();
		//实例化过滤器并设置要过滤的广播
        IntentFilter intentFilter = new IntentFilter(ACTION);
        intentFilter.setPriority(Integer.MAX_VALUE);
        //注册广播
        this.registerReceiver(mSMSBroadcastReceiver, intentFilter);
        L.v("广播注册开启", "广播注册开启");
        mSMSBroadcastReceiver.setOnReceivedMessageListener(new SMSBroadcastReceiver.MessageListener() {
            @Override
            public void onReceived(String message,int type) {
            	if (type==1) {
					//验证码
            		register_sms.setText(message);
				}
            	if (type==2) {
            		//邀请码
            		register_team.setText(message);
				}
            }
        });
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		 this.unregisterReceiver(mSMSBroadcastReceiver);
	}
	
}
